import React, {useEffect, useRef, useState} from 'react';
import useRenderCom from '@/hooks/useRenderCom';
import {
    getRoleListApi,
    insetRoleApi,
    updateRoleApi,
    changeRoleStatusApi,
    getRoleMenuTreeSelectApi
} from "@/api/system/role";
import type {SysRole} from "@/api/system/role";
import {getMenuTreeSelectApi} from "@/api/system/menu";
import {publicFormatTime} from "@/utils";
import FormConfig from "./form-config.json";
import {ComponentMethods} from "@/types/app";
import {message, Modal} from "antd";
import {ExclamationCircleOutlined} from "@ant-design/icons";

const SystemRoleList = () => {
    const {
        renderForm,
        renderTable,
        getFormValue,
        resetFormValue,
        renderDialog,
        setFormSchema,
        checkFormRequire
    } = useRenderCom();
    const [formValue, setFormValue] = useState('');
    const [isLoading, setIsLoading] = useState(false);
    const [loading, setLoading] = useState(false);
    const [total, setTotal] = useState(0);
    const [tableData, setTableData] = useState<SysRole[]>([]);
    const formRef: any = useRef(null);
    const modalFormRef: any = useRef(null);
    const queryListRef = useRef({
        current: 1,
        size: 30
    })

    useEffect(() => {
        getRoleList();
    }, []);

    const getRoleList = () => {
        setLoading(true);
        const formList = getFormValue(formRef.current);
        const params: any = {
            ...formList,
            pageNum: queryListRef.current.current,
            pageSize: queryListRef.current.size,
        }
        if (formList.createTimes && formList.createTimes.length) {
            params["startTime"] = publicFormatTime(formList.createTimes[0], "yyyy-MM-dd");
            params["endTime"] = publicFormatTime(formList.createTimes[1], "yyyy-MM-dd");
            delete params.createTimes
        }
        getRoleListApi(params).then((result) => {
            console.log(result, '000000')
            if (result?.rows) {
                const newData = result.rows.map((ele: any) => ({
                    ...ele,
                    key: ele.roleId,
                    status: ele.status === "0"
                }));
                setTableData(newData);
            } else {
                setTableData([]);
            }
            setTotal(result.total || 0);
        }).finally(() => {
            setLoading(false);
        })
    }

    const handleTable = async (item?: SysRole) => {
        const isEdit = !!(item && item.roleId);
        const roleMenu: any = isEdit
            ? await getRoleMenuTreeSelectApi(item?.roleId)
            : await getMenuTreeSelectApi();
        renderDialog({
            title: `${isEdit ? "编辑" : "新增"}角色`,
            content: renderForm({
                ref: modalFormRef,
                formId: 'dialogForm',
                schema: FormConfig.DialogSchema as any,
                handlers: handlers,
                formList: isEdit ? {
                    ...item,
                    status: item?.status ? "0" : "1",
                    menuIds: roleMenu.checkedKeys
                } : {status: "0"},
            }),
            onOk: (cb: () => void) => {
                const api = isEdit ? updateRoleApi : insetRoleApi;
                checkFormRequire(modalFormRef.current).then((values) => {
                    const params: any = {...values};
                    if (isEdit) {
                        params["roleId"] = item?.roleId
                    }
                    api(params).then((res) => {
                        message.success(`${isEdit ? "编辑" : "新增"}角色成功`);
                        getRoleList();
                        cb && cb();
                    })
                })
            }
        })
        setTimeout(() => {
            const otherSchema = isEdit ? [
                {
                    field: "menuIds",
                    path: "componentProps.checkStrictly",
                    value: item?.menuCheckStrictly
                }
            ] : []
            setFormSchema(modalFormRef.current, [
                {
                    field: "menuIds",
                    path: "componentProps.treeData",
                    value: roleMenu.menus
                },
                ...otherSchema
            ])
        })
    }

    const onHandleClickStatus = (options: any) => {
        const {value, item, record, event} = options;
        Modal.confirm({
            title: "提示",
            icon: <ExclamationCircleOutlined/>,
            content: `确认${value ? "启用" : "停用"}角色【${record.roleName}】?`,
            okText: '确认',
            cancelText: '取消',
            onOk: () => {
                changeRoleStatusApi({
                    status: value ? "0" : "1",
                    roleId: record.roleId
                }).then(() => {
                    message.success(`${value ? "启用" : "停用"}角色【${record.roleName}】成功`);
                    getRoleList();
                }).catch(() => {
                    getRoleList();
                })
            },
            onCancel: () => {
                getRoleList();
            }
        })
        event.nativeEvent.stopPropagation();
    }

    const onHandleButtonGroup = (options: any) => {
        const {item, row, value} = options;
        console.log(item, 'sslslsslssl')
        const obj: any = {
            search: () => {
                getRoleList();
            },
            refresh: () => {
                resetFormValue(formRef.current);
                getRoleList();
            },
            insertRow: () => handleTable(),
            editRow: () => handleTable(row)
        };
        obj[item.field] && obj[item.field]();
    }

    const handlers: ComponentMethods = {
        handleClickStatus: (options: any) => onHandleClickStatus(options),
        handleButtonGroup: (options: any) => onHandleButtonGroup(options.value),
        handleTableClick: ({value}) => onHandleButtonGroup(value)
    }

    return (
        <div className={'h-full flex flex-col'}>
            <div className={'w-full'}>
                {renderForm({
                    ref: formRef,
                    formId: 'filterForm',
                    schema: FormConfig.FilterSchema,
                    handlers: handlers
                })}
            </div>
            <div className={"flex-1 min-h-0 overflow-hidden"}>
                {renderTable<SysRole>({
                    tableHeader: FormConfig.TableHeader as any,
                    tableData: tableData,
                    handlers: handlers,
                    isLoading: loading,
                    queryList: queryListRef.current,
                    total: total,
                })}
            </div>
        </div>
    );
};

export default SystemRoleList;
